package cn.stronglink.assetmanage.business.check.checkorder;


import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import com.luck.picture.lib.tools.Constant;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import cn.stronglink.assetmanage.MyApplication;
import cn.stronglink.assetmanage.R;
import cn.stronglink.assetmanage.business.check.assetlist.AssetListActivity;
import cn.stronglink.assetmanage.dao.DaoManager;
import cn.stronglink.assetmanage.dao.SyncTypesDao;
import cn.stronglink.assetmanage.entity.Check;
import cn.stronglink.assetmanage.entity.MessageEvent;
import cn.stronglink.assetmanage.entity.SyncTypes;
import cn.stronglink.assetmanage.listener.onRecyclerListener;
import cn.stronglink.assetmanage.utils.Constants;
import cn.stronglink.assetmanage.utils.ToastUtil;
import cn.stronglink.assetmanage.utils.dao.CheckDataUtil;
import cn.stronglink.netrequest.business.check.CheckService;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * 未入库表单列表
 * A simple {@link Fragment} subclass.
 */
public class UnCheckFragment extends Fragment implements onRecyclerListener {

    private Unbinder mUnbinder;
    @BindView(R.id.rv_uncheck)
    RecyclerView rvUnCheck;
    @BindView(R.id.sfl_uncheck_order)
    SwipeRefreshLayout sflUncheckOrder;
    private CheckOrderAdapter mOrderAdapter;
    private List<Check> unCheckList;
    private CheckService mCheckService;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_un_check, container, false);
        mUnbinder = ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initViewAndData();
    }

    private void initViewAndData() {
        mOrderAdapter = new CheckOrderAdapter(getActivity());
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity(), LinearLayout.VERTICAL,
                false);
        rvUnCheck.setLayoutManager(layoutManager);
        rvUnCheck.setAdapter(mOrderAdapter);
        mOrderAdapter.setListener(this);
        sflUncheckOrder.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refreshUncheckData();
            }
        });
        mCheckService = new CheckService();
        //显示本地数据
        showUnCheckData();
    }


    private void showUnCheckData() {
        unCheckList = CheckDataUtil.getunCheckOrderNoDistince();
        if (mOrderAdapter != null) {
            mOrderAdapter.notifyDataChanged(unCheckList);
        }
    }

    /**
     * 刷新未入库数据
     */
    private void refreshUncheckData() {
        //判断是离线还是在线
        SyncTypes syncTypes = DaoManager.getDaoSession(this.getActivity()).getSyncTypesDao().
                queryBuilder().where(SyncTypesDao.Properties.IsSelected.eq(true)).unique();
        int tp = 0;
        if (syncTypes != null) {
            tp = syncTypes.getSyscTs();
        }
        switch (tp) {
            case Constants.STATUS_ONE:
                //自动
                CheckDataUtil.getLocalCheckList();
                getCheckData();
                break;
            case Constants.STATUS_TWO:
                //离线，从数据库拿数据
                stopRefresh();
                ToastUtil.toastShort("本地数据加载完成");
                break;
            default:
                break;
        }
    }

    private void stopRefresh() {
        if (sflUncheckOrder != null) {
            sflUncheckOrder.setRefreshing(false);
        }
    }

    private void getCheckData() {
        if (mCheckService != null) {
            try {
                mCheckService.downloadPresetWorkOrder(new Callback() {
                    @Override
                    public void onFailure(Call call, final IOException e) {
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                stopRefresh();
                                ToastUtil.toastShort(e.getMessage());
                            }
                        });
                    }

                    @Override
                    public void onResponse(Call call, final Response response) throws IOException {
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                stopRefresh();
                            }
                        });
                        saveCheckData(response);
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void saveCheckData(Response response) {
        try {
            if (response.isSuccessful()) {
                if (response.code() == 200) {
                    final String json = response.body().string();
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (json != null && !"".equals(json)) {
                                CheckDataUtil.saveCheckData(json);
                                ToastUtil.toastShort("更新完成");
                                showUnCheckData();
                                //通知Activity更新数据
                                MessageEvent messageEvent = new MessageEvent();
                                messageEvent.setType(Constants.UPDATE_CHECK_DATA);
                                EventBus.getDefault().post(messageEvent);
                            } else {
                                ToastUtil.toastShort(MyApplication.APP_CONTEXT.getString(R.string.get_no_data));
                            }
                        }
                    });
                } else {
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            ToastUtil.toastShort(MyApplication.APP_CONTEXT.getString(R.string.get_data_fail));
                        }
                    });
                }
            } else {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        ToastUtil.toastShort(MyApplication.APP_CONTEXT.getString(R.string.get_data_fail));
                    }
                });

            }
        } catch (final Exception e) {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    ToastUtil.toastShort(e.getMessage());
                }
            });
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mUnbinder.unbind();
    }

    @Override
    public void onItemClicked(View v, int postion) {
        //跳转到UnCheckAsset界面
        Intent intent = new Intent(getActivity(), AssetListActivity.class);
        intent.putExtra(Constants.CHECK_ORDER, unCheckList.get(postion).getId_());
        startActivity(intent);
    }
}
